//
//  Status.swift
//  sinaWeibo
//
//  Created by 张国梁 on 16/4/13.
//  Copyright © 2016年 CoderGL. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {
    
    var created_at: String?{
        didSet{
            let createDate = NSDate.dateWithStr(created_at!)
            created_at = createDate.descDate
        }
    }
    var id: Int = 0
    var text: String?
    var source: String?{
        didSet{
            if source == "" {
                return
            }
            let startLocation = (source! as NSString).rangeOfString(">").location + 1
            
            let length = (source! as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startLocation
            
            source = "来自 " + (source! as NSString).substringWithRange(NSMakeRange(startLocation, length))
        }
    }
    var pic_urls: Array<[String : AnyObject]>?{
        
        didSet{
            
            // 1.初始化数组
            storedPicURLS = [NSURL]()
            bmiddlePicURLs = [NSURL]()
            // 2.遍历取出所有的图片路径字符串
            for dict in pic_urls!
            {
                if var urlStr = dict["thumbnail_pic"]
                {
                    
                    // 将字符串转换为URL保存到数组中
                    storedPicURLS?.append(NSURL(string: urlStr as! String)!)
                    
                    urlStr = (urlStr as! NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
                    bmiddlePicURLs?.append(NSURL(string: urlStr as! String)!)
                }
            }
        }
    }
    var storedPicURLS: [NSURL]?
    var bmiddlePicURLs: [NSURL]?
    var user: User?
    var retweeted_status: Status?
    var rowH: CGFloat = 0.0
    
    
    
    
    
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if "user" == key {
            user = User(dict: value as! [String: AnyObject])
            return
        }
        
        if "retweeted_status" == key {
            retweeted_status = Status(dict: value as! [String: AnyObject])
            return
        }
        
        super.setValue(value, forKey: key)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    
    
    class func loadStatus(since_id: Int, max_id: Int, finished:(models: Array<Status>?, error: NSError?)->()) {
        let urlStr = "2/statuses/home_timeline.json"
        var params = ["access_token" : UserAccount.getAccountInfo()!.access_token!]
        
        if since_id != 0 {
            params["since_id"] = "\(since_id)"
        }
        
        if max_id != 0 {
            params["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.shareNetworkTools().GET(urlStr, parameters: params, progress: nil, success: { (_, JSON) in
            print(UserAccount.getAccountInfo()!.access_token!)
            // 字典数组转模型数组
            let models = json2model(JSON!["statuses"] as! [[String : AnyObject]])
            
            finished(models: models, error: nil)
            // 缓存图片
//            cacheImages(models, finished: finished)
            
        }) { (_, error) in
            finished(models: nil, error: error)
        }
    }
    class func json2model(list: [[String : AnyObject]]) -> Array<Status> {
        var models = Array<Status>()
        for dict in list {
            models.append(Status(dict: dict))
        }
        return models
    }
    
    // 缓存图片暂时没有用
    class func cacheImages(models: Array<Status>, finished:(models: Array<Status>?, error: NSError?)->()) {
        let group = dispatch_group_create()
        
        for var status in models {
            status = status.retweeted_status != nil ? status.retweeted_status! : status
            for url in status.storedPicURLS! {
                if SDWebImageManager.sharedManager().cachedImageExistsForURL(url) {
                    continue
                }
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) in
                    dispatch_group_leave(group)
                    
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            //        传给外界
            finished(models: models, error: nil)
        }
    }
    
    // 计算pictureView的尺寸
    func calculateImageSize() -> CGSize {
        let count = storedPicURLS?.count
        
        if count<1 || count == nil {
            return CGSizeZero
        }
        
        if count == 1 {
//            let key = storedPicURLS?.first?.absoluteString
//             let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return SinglePicSize
        }
        
        if count>1 && count<4 {
            return CGSizeMake(width, width/3.0)
        }
        if count == 4 {
            return CGSizeMake(width/3.0 * 2.0, width/3.0 * 2.0)
        }
        
        if count>4 && count<7 {
            return CGSizeMake(width, width/3.0 * 2.0)
        } else {
            
            return CGSizeMake(width, width)
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
